<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { getOrderDetailAPI } from '@/api/room'
  import { useUserStore } from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'
  import RoomStatus from './components/room-status.vue'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RateInfo from './components/rate-info.vue'
  import { nextTick, ref } from 'vue'
  import type { OrderDetail } from '@/types/consult'
  import type { Datum, MsgItem } from '@/types/room'
  import { upLoadImageAPI } from '@/api/consult'
  import COS from 'cos-js-sdk-v5'

  // console.log(COS.version);  sdk 版本需要不低于 1.8.3
  const cos = new COS({
    SecretId: 'AKIDGZgcMuGOJ1XpumSuBF7lCQSJxYw74oX3', // sts服务下发的临时 secretId
    SecretKey: 'NZaOzNZYMxLWTDk4D9sOhmgNrBKH9wb9', // sts服务下发的临时 secretKey
  })

  //获取存储用户的仓库
  const store = useUserStore()

  //装备一个变量存储发送信息
  const msg = ref('')

  //定义props接收参数
  interface Props {
    orderId: string
    payResult: string //支付结果
  }
  const props = defineProps<Props>()

  //定义变量接收信息
  const msgList = ref<MsgItem[]>([])

  let socket: Socket
  // 1. 引入socket.io-client
  onLoad(async () => {
    //支付不成功则返回我的页面
    if (props.payResult === 'false') {
      uni.switchTab({ url: 'pages/my/my' })
      return
    }
    //支付成功则连接医生
    // 2. 建立连接
    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })

    socket.on('connect', () => {
      // 建立连接成功
      console.log('连接建立成功')
    })

    // 监听订单状态改变
    socket.on('statusChange', () => {
      // console.log('订单状态改变')
      getOrderInfo()
    })

    //监听服务器发过来的历史消息
    socket.on('chatMsgList', (data) => {
      if (data.code != 10000) return
      data.data.forEach((item: Datum) => {
        msgList.value.push(
          // 构造一条数据，显示时间节点
          {
            msgType: 31,
            msg: { content: item.createTime },
            id: item.createTime,
          },
          ...item.items!
        )
      })
      console.log('data --->', data)
      // 用延时器等dom渲染完毕后再滚动到底部
      nextTick(() => {
        lastId.value = 'item' + (msgList.value.length - 1)
      })
    })

    //监听服务器发过来的即时消息
    socket.on('receiveChatMsg', (data) => {
      msgList.value.push(data)
      // 用延时器等dom渲染完毕后再滚动到底部
      nextTick(() => {
        lastId.value = 'item' + (msgList.value.length - 1)
      })
    })
  })

  //定义函数发送信息
  const sendMsg = () => {
    //发送消息
    socket.emit('sendChatMsg', {
      msg: { content: msg.value },
      msgType: 1,
      from: store.userId,
      to: orderInfo.value.docInfo.id!,
    })
    //清空输入框
    msg.value = ''
  }

  //定义函数发送图片
  const sendPhoto = async () => {
    // 是否在问诊状态中...
    if (orderInfo.value?.status !== 3) {
      return uni.showToast({ title: '医生当前不在线!' })
    }
    //选择图片
    const res = await uni.chooseImage()
    console.log('res --->', res)
    //上传图片
    const res2 = await upLoadImageAPI(res.tempFilePaths[0])
    console.log('res2 --->', res2)
    //发送图片
    socket.emit('sendChatMsg', {
      msg: { picture: { id: res2.id, url: res2.url } },
      msgType: 4,
      from: store.userId,
      to: orderInfo.value.docInfo.id!,
    })
  }

  //定义函数发送视频
  const sendVideo = async () => {
    // 是否在问诊状态中...
    if (orderInfo.value?.status !== 3) {
      return uni.showToast({ title: '医生当前不在线!' })
    }
    //选择视频
    const res = await uni.chooseVideo()
    console.log('res --->', res)
    cos.uploadFile(
      {
        Bucket: 'cyz-hm03-1333985826' /* 填写自己的 bucket，必须字段 */,
        Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
        Key: '测试.mp4' /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
        Body: res.tempFile, // 上传文件对象
        onProgress: function (progressData) {
          console.log(JSON.stringify(progressData))
        },
      },
      function (err, data) {
        if (err) {
          console.log('上传失败', err)
        } else {
          //发送图片
          socket.emit('sendChatMsg', {
            msg: { picture: { id: Date.now(), url:'https://' + data.Location } },
            msgType: 4,
            from: store.userId,
            to: orderInfo.value.docInfo.id!,
          })
        }
      }
    )
  }

  //定义订单详情变量
  const orderInfo = ref({} as OrderDetail)

  //定义函数获取订单详情
  const getOrderInfo = async () => {
    const res = await getOrderDetailAPI(props.orderId)
    orderInfo.value = res
  }

  //离开页面时获取订单详情
  onLoad(() => {
    getOrderInfo()
  })

  //定义一个状态变量存储id
  const lastId = ref('')
</script>

<template>
  <view class="room-page">
    <RoomStatus :status="orderInfo.status" :countdown="orderInfo.countdown" />
    <scroll-view
      scroll-with-animation
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="lastId"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <view v-for="(item, index) in msgList" :key="item.id" :id="'item' + index">
          <!-- 患者信息 -->
          <PatientInfo :info="item.msg?.consultRecord" v-if="item.msgType === 21" />
          <!-- 系统提醒话语 -->
          <NotifyInfo v-if="item.msgType!>=31" :type="item.msgType!">
            {{ item.msg?.content }}
          </NotifyInfo>
          <!-- 图片以及文字信息 -->
          <MessageInfo
            :info="item"
            :type="item.msgType"
            v-if="item.msgType === 4 || item.msgType === 1"
          />
          <!-- 处方信息 -->
          <PrescriptionInfo :info="item.msg" v-if="item.msgType === 22" />
          <!-- 评价信息 -->
          <RateInfo
            :orderId="orderId"
            :docId="orderInfo.docInfo.id!"
            :info="item.msg!"
            v-if="item.msgType === 23 || item.msgType === 24"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderInfo.status !== 3"
          v-model="msg"
          @confirm="sendMsg"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons @click="sendPhoto" size="40" color="#979797" type="image"></uni-icons>
        </view>
        <view class="image-button">
          <uni-icons @click="sendVideo" size="40" color="#979797" type="videocam"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
